<?php

namespace app\api\controller;

use app\admin\model\Contrant;
use app\admin\model\Location;
use app\admin\model\Record;
use app\admin\model\Sendauto;
use app\admin\model\Send;
use app\common\controller\Api;
use app\admin\model\Policy;
use app\admin\model\Rule;
use app\admin\model\User;
use app\admin\model\Notifylog;
use addons\epay\library\Service;
use app\common\model\MoneyLog;


/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 隐私政策
     *
     */
    public function policy($status= 0 )
    {
        $policy = Policy::where('status', $status)->find();
        $this->success('请求成功', $policy);
    }
    /**
     * 收费规则
     * @param mixed $page
     * @return void
     */
    public function rule($page= 1,$type = 0)
    {
      
        if($type > 1) {
            $this->error('fail');
        }
       
        $rule = Rule::where(['status' => 1,'type' => $type])->order('id desc')->paginate(15,false,['page' => $page]);
        $this->success('请求成功',  $rule);
    }
    /**
     * 首页汇总
     * Summary of getTotal
     */
    public function getTotal()
    {
         $total = Location::count();
         $use = Location::where(['status' => 1])->count();
         $this->success('suc',['total' =>  $total,'free' =>  $total - $use ,'use' =>  $use ]);
    }
    //获取车位情况
    public function getFree($where = '',$page = 1,$type = 0)
    {
        $option['status'] = 0;
        if($where) {
            $option['location'] = ['LIKE',"%$where%"];
            unset($option['status']);
        }
        if($type == 1) {
            unset($option['status']);
            $option = [];
        }
        // if($type == 4) {//我的车位
           
        //     $option['status'] = 1; 
        // }
        $list = Location::where($option)->paginate(20,false,['page' => $page]);
      
        $list->each(function($item){
            $item['detail'] = '';
            if($item['status'] == 1) {//如果=1就是在使用中
                $item['detail'] = Record::where(['location_id'=> $item['id'],'status' => ['in',[1,2]]])->find();
            }
        });
       
        $this->success('suc', $list);
    }
    public function detail($id)
    {
        $this->success('suc', Location::find($id));
    }
    //在支付回调
    public function notify()
    {
        error_reporting(0);
        $data = file_get_contents("php://input");
      
        Notifylog::insert(['detail' => $data,'time' => time(),'type' => 1]);
        
        $paytype = 'wechat';
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        //微信支付V3返回和V2不同
        if (Service::isVersionV3() && $paytype === 'wechat') {
            $data = $data['resource']['ciphertext'];
            $data['total_fee'] = $data['amount']['total'];
        }
        //获取支付金额、订单号
        $payamount = $data['total_fee'] / 100;
        $out_trade_no = $data['out_trade_no'];
        $detail = Record::where(['order_id' =>  $out_trade_no])->find();//订单详情
        if(empty($detail)) return false;//如果订单不存在
        if($detail->status) {//已经修改了
            return true;
        }
        $detail->status = 1;
        $detail->pay_time = time();
        $detail->pay_money = $payamount;
        Location::where(['id' =>  $detail['location_id']])->update(['status' => 1]);
        if($detail['type'] == 1) {//如果是超时订单
            $detail->status = 3;
            MoneyLog::addMoney($detail['master_id'],$detail->pay_money ,'停车费用');
            $controller = new \app\api\controller\Notify();
            $_GET['orderId'] = $out_trade_no;
            $controller->getResult();
        }
        $detail->save();
        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    public function autoSend()
    {
        set_time_limit(0);
        $list = User::where(['group_id' => 1,'auto_set' => 1])->select();

        if(empty($list)) $this->error('没有自动发布设置');//如果没有就不做任何处理
        $date = date('w');//星期几
        Sendauto::where(['date' =>  $date])->update(['status' => 0]);
    
        foreach($list as $value) {
            $insertData = [];
            $record =  Sendauto::where(['user_id' => $value['id'],'date' =>  $date,'status' => 0])->select();//自动发布的用户
          
            if(empty($record)) continue;
         
            $location = Location::where(['user_id' => $value['id']])->select();//这个用户的车位，正常是一个，也可能的多个
          
            if(empty($location)) continue;
            foreach($location as $locationValue) {//车位
               
                foreach($record as $recordValue) {
                    if($locationValue['user_id'] == $recordValue['user_id']) {
                  
                        $beginTime = date('Y-m-d'). ' '.$recordValue['begin_time'];
                        $endTime = date('Y-m-d'). ''.$recordValue['end_time'];
                     
                        $insertData[] = [
                            'user_id' => $locationValue['user_id'],
                            'begin_time' =>  strtotime($beginTime ) ,
                            'end_time' =>  strtotime($endTime ) ,
                            'date' => date('Y-m-d'),
                            'location_id' => $locationValue['id'],
                            'location' => $locationValue['location'],
                        ]; 
                    }
                }
            }
          
            Send::InsertAll( $insertData); 
            Sendauto::where(['user_id' => $value['id'],'date' =>  $date,'status' => 0])->update(['status' => 1]);
            unset($insertData);
         
        }
       $this->success('suc');//如果没有就不做任何处理
    }
    public function contrant()
    {
        $this->success('suc',Contrant::select());
    }

  


}
